package cs2340.droidceptiontodo;


import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.content.Intent; 
/**
 * This class edits a to-do item and saves the changes
 * It is accessible through the view_todoitem.xml screen and returns
 * the user to that screen with any updated information displayed
 *
 */
public class EditToDoItemActivity extends Activity implements OnClickListener 
	{
		public static ToDoItem item; // The current item to edit
		
		Database itemwriter;
	    // EditText fields
	    EditText itemName;
	    EditText description;
	    EditText category;
	    EditText location;
	    
	    // Date Picker Dialog variables
	    boolean hasDueDate;
	    static final int DATE_DIALOG_ID = 0;
		int month;
		int day;
		int year;
		TextView dateView; 	
		
		// Time Picker Dialog variables
		boolean hasDueTime;
		static final int TIME_DIALOG_ID = 1;
		int hour;
		int minute;
		String amPM;
		TextView timeView;
	    
	    // Buttons
		Button editToDoItem;
		Button cancel;
		
	    Button chooseDateButton;
	    Button clearDateButton;
	    
	    Button chooseTimeButton;
	    Button clearTimeButton;
	    // Listener for date picker dialog
		DatePickerDialog.OnDateSetListener dateSetListener =
		        new DatePickerDialog.OnDateSetListener() {
	            @Override
				public void onDateSet(DatePicker view, int yearSelected, 
	                              int monthOfYear, int dayOfMonth) {
		            year = yearSelected;
		            month = monthOfYear + 1; // Month is 0 based so add 1
		            day = dayOfMonth;
		        	hasDueDate = true;
		            updateDateDisplay();
	            }
	    };
	    // Listener for time picker dialog
	    private TimePickerDialog.OnTimeSetListener timeSetListener =
	    	    new TimePickerDialog.OnTimeSetListener() {
	    	        @Override
					public void onTimeSet(TimePicker view, int hourOfDay, int minuteSelected) {
	    	            hour = hourOfDay;
	    	         // Convert from military time
	    				amPM = "am";
	    				if (hour >= 12) {
	    					if (hour > 12) {
	    						hour = hour-12;
	    					}
	    					amPM = "pm";
	    				}
	    				if (hour == 0) {
	    					hour = 12;
	    					amPM = "am";
	    				}
	    	            minute = minuteSelected;
	    	            hasDueTime = true;
	    	            updateTimeDisplay();
	    	        }
	    	    };
	    /** 
	     * Called when the activity is first created. 
	     * Places old information in text fields for the user to edit
	     */
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.edit_todoitem);
	        Log.d("DEBUG","Starting AddToDoItem Activity");
	        //itemwriter = new Database(this);
	        itemwriter = Database.getInstance(this);
	        itemName = (EditText)findViewById(R.id.name);
	        itemName.setText(item.getName());
	        
	        hasDueDate = item.hasDueDate();
	        hasDueTime = item.hasDueTime();
	        final Calendar c = Calendar.getInstance();
	        if (hasDueDate) {
	        	// Initialize date and time to item's date and time
	        	String dueDate = item.getDueDate();
	        	char[] dateArr = dueDate.toCharArray();
	        	year = Integer.parseInt("" + dateArr[6] + dateArr[7] + dateArr[8] + dateArr[9]);
		        month = Integer.parseInt("" + dateArr[0] + dateArr[1]);
		        day = Integer.parseInt("" + dateArr[3] + dateArr[4]);
	        }
	        else {	        	        
		        year = c.get(Calendar.YEAR);
		        month = c.get(Calendar.MONTH);
		        day = c.get(Calendar.DAY_OF_MONTH);
		        
	        }
	        if (hasDueTime) {
	        	String dueTime = item.getDueTime();
	        	int concat = dueTime.indexOf(":");
	        	String hr = dueTime.substring(0, concat);
	        	hour = Integer.parseInt(hr);
	        	minute = Integer.parseInt(dueTime.substring(concat + 1, concat+3));
	        	amPM = dueTime.substring(dueTime.length() -2, dueTime.length());
	        	char[] timeArr = dueTime.toCharArray();
	        	//hour = Integer.parseInt("" + timeArr[0] + timeArr[1]);
		        //minute = Integer.parseInt("" + timeArr[3] + timeArr[4]);
		        //amPM = "" + timeArr[6] + timeArr[7];
	        }
	        else {
	        	hour = c.get(Calendar.HOUR_OF_DAY);
		        // Convert from military time
		        amPM = "am";
				if (hour >= 12) {
					if (hour > 12) {
						hour = hour-12;
					}
					amPM = "pm";
				}
				if (hour == 0) {
					hour = 12;
					amPM = "am";
				}
		        minute = c.get(Calendar.MINUTE);
	        }
	        
	        // Date
	        chooseDateButton = (Button)findViewById(R.id.chooseDateButton);
	        chooseDateButton.setOnClickListener(this);
	        clearDateButton = (Button)findViewById(R.id.clearDateButton);
	        clearDateButton.setOnClickListener(this);
	        dateView = (TextView)findViewById(R.id.dateView);
	        if (hasDueDate) {
	        	dateView.setText(item.getDueDate().toString());
	        }
	        else {
	        	dateView.setText("None");
	        }
			
	        // Time
	        chooseTimeButton = (Button)findViewById(R.id.chooseTimeButton);
	        chooseTimeButton.setOnClickListener(this);
	        clearTimeButton = (Button)findViewById(R.id.clearTimeButton);
	        clearTimeButton.setOnClickListener(this);
	        timeView = (TextView)findViewById(R.id.timeView);
	        if (hasDueTime) {
	        	timeView.setText(item.getDueTime().toString());
	        }
	        else {
	        	timeView.setText("None");
	        }
	        
	        description = (EditText)findViewById(R.id.description);
	        description.setText(item.getDetails());
	        category = (EditText)findViewById(R.id.category);
	        category.setText(item.getCategory().toString());
	        location = (EditText)findViewById(R.id.location);
	        location.setText(item.getLocation());
	        
	        editToDoItem = (Button)findViewById(R.id.editItemButton);
	        cancel = (Button)findViewById(R.id.cancelButton);
	        editToDoItem.setOnClickListener(this);
	        cancel.setOnClickListener(this);
	}
	    // Updates date displayed to the user
    private void updateDateDisplay() {
        dateView.setText(
            new StringBuilder()
                    .append(month).append("/")
                    .append(day).append("/")
                    .append(year).append(" "));
    }
    	// Updates time displayed to the user
    private void updateTimeDisplay() {
       	timeView.setText(
    		        new StringBuilder()
    		                .append(pad(hour))
    		                .append(":")
    		                .append(pad(minute))
    		                .append(" ")
    		                .append(amPM));
    	
    }
    private static String pad(int c) {
    	if (c >= 10) {
    		return String.valueOf(c);
    	}
        else {
        	return "0" + String.valueOf(c);
        }
   	}
    // Determines which dialog to display
    @Override
	protected Dialog onCreateDialog(int id) {
        switch (id) {
        	case DATE_DIALOG_ID:
        		return new DatePickerDialog(this,dateSetListener,
        				year, month, day);
        	case TIME_DIALOG_ID:
        		return new TimePickerDialog(this,timeSetListener, 
        				hour, minute, false);
        }
        return null;
    }
    /**
     * called when the editToDoItem or cancel buttons are clicked
     */
	@Override
	public void onClick(View v) {
		//AddToDoItem account button has been clicked
	    if(v.getId() == (editToDoItem.getId())) {
			//Receive item name input text from itemName text field
			String itemNameStr = itemName.getText().toString();
			//Receive date input text from date picker
			String dateStr = "";
			if (hasDueDate) {
				 dateStr = String.format("%02d/%02d/%04d", month, day, year);
			}
			
			//Receive time input text from time picker
			String timeStr = "";
			if (hasDueTime) {
				timeStr = String.format("%d:%02d " + amPM, hour, minute);
			}
			//Receive description  input text from edittext10
			String descriptionStr = description.getText().toString();
			//Receive category input text from edittext11
			String categoryStr = category.getText().toString();
			//Receive location input text from edittext12
			String locationStr = location.getText().toString();
			Log.d("DEBUG","itemNameStr "+itemNameStr);
			Log.d("DEBUG","dateStr "+dateStr);
			Log.d("DEBUG","timeStr "+timeStr);
			Log.d("DEBUG","descriptionStr "+descriptionStr);
			Log.d("DEBUG","categoryStr "+categoryStr);
			Log.d("DEBUG","locationStr "+locationStr);
			
			
			// update item
			item.setName(itemNameStr);
			item.setDetails(descriptionStr);
			item.setCategory(categoryStr);
			item.setDueDate(dateStr);
			item.setDueTime(timeStr);
			item.setLocation(locationStr);
			
			// Save the updated item
			Log.d("Debug", "item created...");
			try{
				itemwriter.open();
				itemwriter.updateItem(item);
				itemwriter.close();
			}catch(Exception e){
				Log.d("Debug", e.toString());
			}
			
			TextView tv = (TextView)findViewById(R.id.addtodoinfo);
			tv.setText("ToDoItem addition successful!");
			
			//Go back to detail view
			ViewToDoItemActivity.item = item;
			Intent i = new Intent();                 
    		i.setClassName("cs2340.droidceptiontodo", "cs2340.droidceptiontodo.ViewToDoItemActivity"); 
     		startActivity(i); 
		}
	    //This is the case of Cancel button being clicked
		else if (v.getId() == (cancel.getId())){
			// Do not save the item, return to detailed view
			Intent i = new Intent();                 
    		i.setClassName("cs2340.droidceptiontodo", "cs2340.droidceptiontodo.ViewToDoItemActivity"); 
     		startActivity(i); 
			
		}
		else if (v.getId() == (chooseDateButton.getId())){
            showDialog(DATE_DIALOG_ID);
		}
		else if (v.getId() == (clearDateButton.getId())) {
			hasDueDate = false;
	        dateView.setText("None");
		}
		else if (v.getId() == (chooseTimeButton.getId())) {
			showDialog(TIME_DIALOG_ID);
		}
		else if (v.getId() == (clearTimeButton.getId())) {
			hasDueTime = false;
			timeView.setText("None");
		}
	}
	public Database getDatabase() {
		return itemwriter;		
	}
}